<?php
namespace Business\Controller;
use Think\Controller;
class BaseController extends Controller {
	
	public static $wx;//缓存微信对象
	protected function _initialize(){

		if(!strpos($_SERVER["HTTP_USER_AGENT"],"MicroMessenger")){
			$this->diemsg(0,'请使用微信浏览器访问本应用！');
		}
		
		$options['appid']=C('BB_APPID_business');
		$options['secret']=C('BB_SECRET_business');
		self::$wx=new \bb\Wechat($options);

		//unset($_SESSION);
		if(!$_SESSION['business']['openid']){
			if(I('code')){
				$d=self::$wx->getOauthAccessToken();
				$u=self::$wx->user($d['openid']);
				$_SESSION['business'] = $u;
				if($u['subscribe']){//关注
					$openid=$_SESSION['business']['openid']=$u['openid'];
					$_SESSION['business']['wxuser']=$u;
					$_SESSION['business']['set']['url']=C('BB_URL');
					//=================================
				}else{
					//没有关注公众号跳转到关注页面
					$url="http://mp.weixin.qq.com/s?__biz=MzA3MTQwNjA0NA==&mid=401013803&idx=1&sn=ff7f8f1a5d02713b062c925a1c72bff1#rd";
					header("Location:".$url);
					exit;
				}
			}else{
				$url=$this->snsapi_base();
				header("location:".$url);
			}
		}
		
		$shop=M('bb_shop')->where(array('wx_openid'=>$_SESSION['business']['openid']))->find();
		if(!$shop){
			//存在openid 跳转到登录页面
			if($_SESSION['business']['openid']){
				header("Location:".U('Business/Login/login'));
				exit;
			}else{
				$this->diemsg(0,'获取openid 出错！');
			}
		}else{
			$_SESSION['business']['shop']=$shop;
		}
	}
	//静默授权URl
	public function snsapi_base(){
		$oa_url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		return self::$wx->getOAuthRedirect($oa_url,'xybingbing');
	}
	//停止不动的信息通知页面处理
	public function diemsg($status,$msg){
		//成功为1，失败为0
		$status=$status?$status:'0';
		$this->assign('status',$status);
		$this->assign('msg',$msg);
		$this->display('Base_diemsg');
		die();
	}
	//百度根据坐标找位置
	private function get_position_pc($zb=''){
		if($zb){
			$url = 'http://api.map.baidu.com/geocoder?location='.$zb['latitude'].','.$zb['longitude'].'&coord_type=bd09ll&output=json&src=jt';
			$addressData = get_curl($url);
			$address = json_decode($addressData,true);
			if($address['status']=='OK'){
				$addres['address']=$address['result']['formatted_address'];
				$addres['longitude']=$address['result']['location']['lng'];
				$addres['latitude']=$address['result']['location']['lat'];
				$addres['province']=$address['result']['addressComponent']['province'];		//省
				$addres['city']=$address['result']['addressComponent']['city'];						//市
				$addres['district']=$address['result']['addressComponent']['district'];			//区
				return $addres;
			}else{
				return FALSE;
			}
		}
	}
}